<template>
  <div>
    <div ref="captureArea" style="width: 750px; position: fixed; right: 100px; top: -2000px; background: #fff;">
      <div><img :src="item.image1" style="width: 100%;"></div>
      <div style="display: flex; padding: 20px; justify-content: space-between; align-items: center;">

        <div style="width: 350px;">
          <div style="font-size: 28px; margin-bottom: 10px;">{{item.title}}</div>
          <div style="display: flex; font-size: 24px;">
            <div><img :src="all.left_pic" style="width: 40px; height: 40px; border-radius: 20px; margin-bottom: 10px; margin-right: 10px;"></img></div>
            <div>{{all.store_name}}</div>
          </div>
          <div style="color: rgb(175, 179, 188); font-size: 20px;">长按识别二维码 进入下单链接</div>
        </div>

        <div style="text-align: center;">
          <div style="width: 150px; height: 150px; margin-bottom: 10px;" id="erweimadiv"></div>
          <div>查询</div>
        </div>
        <div style="text-align: center;">
          <div style="width: 150px; height: 150px; margin-bottom: 10px;" id="erweimadiv2"></div>
          <div>下单</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import html2canvas from 'html2canvas'
  import QRCode from 'qrcodejs2'
  import * as qiniu from 'qiniu-js'
  export default {
    props: ['item'],
    data() {
      return {
        all:""
      }
    },
    created() {

    },
    mounted() {
      this.getinfo()

    },
    methods: {
      getinfo: function() {
        let url = `/own/mstore/info`
        axios.get(url).then((response) => {
          if (response.data.msg.code == 0) {
            this.all = response.data.data

            let p0 = new Promise((res,rej)=>{
              var qrcode = new QRCode(document.getElementById('erweimadiv'), {
                  text: `${location.origin}/h5/query_order`,
                  width: 150,
                  height: 150,
                  colorDark : "#000000",
                  colorLight : "#ffffff",
                  correctLevel : QRCode.CorrectLevel.H
              })
              var qrcode = new QRCode(document.getElementById('erweimadiv2'), {
                  text: `${location.origin}/h5/order?id=${this.item.id}`,
                  width: 150,
                  height: 150,
                  colorDark : "#000000",
                  colorLight : "#ffffff",
                  correctLevel : QRCode.CorrectLevel.H
              })
              res('ok')
            })
            p0.then(()=>{
              this.capture()
            })
          }
        })
      },
      capture() {
        html2canvas(this.$refs.captureArea, {
          useCORS: true,
          scale: 2
        }).then(canvas => {

          // const link = document.createElement('a')
          // link.href = canvas.toDataURL('image/png')
          // link.download = 'screenshot.png'
          // link.click()


          this.uploadok(this.base64ImgtoFile(canvas.toDataURL('image/png')))

        })
      },

      getRandomChar:function(len = 11)  {
        var  x = "0123456789qwertyuioplkjhgfdsazxcvbnm" // 需要什么字符这里添加
        var  tmp = ""
        var timestamp = new Date().getTime();
        for(var  i=0;i<len;i++)  {
          tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
        }
        return  timestamp+tmp;
      },

      base64ImgtoFile(dataurl, filename = 'file') {
              //将base64格式分割：['data:image/png;base64','XXXX']
              const arr = dataurl.split(',')
              // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
              // image/png
              const mime = arr[0].match(/:(.*?);/)[1]  //image/png
              //[image,png] 获取图片类型后缀
              const suffix = mime.split('/')[1] //png
              const bstr = atob(arr[1])   //atob() 方法用于解码使用 base-64 编码的字符串
              let n = bstr.length
              const u8arr = new Uint8Array(n)
              while (n--) {
                  u8arr[n] = bstr.charCodeAt(n)
              }
              return new File([u8arr], `${filename}.${suffix}`, {
                  type: mime
              })
      },
      uploadok: function(file) {
        let name = this.getRandomChar() + '.' + file.name.split('.')[1]
        var that = this
        axios.post(`/api/qiniu/uploadtoken`,{name:name})
          .then(response => {
            if(response.data.msg.code == 0){
              const observer = {
                next(res){
                  console.log(res)
                },
                error(err){
                  console.log(err)
                },
                complete(res){
                  that.$emit('guanbiloadlog')
                  var ua = window.navigator.userAgent.toLowerCase();
                  if (ua.match(/micromessenger/i) == 'micromessenger') {
                    location.href = 'https://gperson.gantanhaokeji.top/'+ res.key
                  }else{
                    location.href = 'https://gperson.gantanhaokeji.top/'+ res.key + '?attname='
                  }
                }
              }
              const observable = qiniu.upload(file,name, response.data.data.token, {}, {})
              const subscription = observable.subscribe(observer) // 上传开始
            }else{
              that.$emit('guanbiloadlog')
              this.$message.error(response.data.msg.info);
            }
          });
      },



      // let p0 = new Promise((res,rej)=>{
      //   var url2 = `${location.origin}/h5/order?id=${item.id}`

      //   if(document.getElementById('erweimadiv')){
      //     document.getElementById('erweimadiv').innerHTML = ""
      //     d = document.getElementById('erweimadiv')
      //   }else{
      //     d = document.createElement('div')
      //     d.setAttribute('id','erweimadiv')
      //     document.body.appendChild(d)
      //   }

      //   var qrcode = new QRCode(document.getElementById('erweimadiv'), {
      //       text: url2,
      //       width: 220,
      //       height: 220,
      //       colorDark : "#000000",
      //       colorLight : "#ffffff",
      //       correctLevel : QRCode.CorrectLevel.H
      //   })
      //   var canvas = document.getElementById("erweimadiv").getElementsByTagName("canvas")[0];
      //   img2x = canvas.toDataURL("image/png");

      //   document.getElementById("erweimadiv").style.position = 'absolute'
      //   document.getElementById("erweimadiv").style.left = '-1000px'

      //   res('ok')

      // if (item.share_img) {
      //   img.src = item.share_img

      //   img22.src = that.all.left_pic

      //   var ua = window.navigator.userAgent.toLowerCase();
      //   if (ua.match(/micromessenger/i) == 'micromessenger') {
      //     //若是微信环境
      //     const blob = that.base64ImgtoFile(url)
      //     that.uploadok(blob)

      //   } else {
      //     //若不是微信环境


      //     // console.log(window.Android)
      //     // var isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('android') > -1 || ua.indexOf('Adr') > -1;
      //     // if (isAndroid) {
      //     //   window.Android.toast('开始下载图片，请等待...')

      //     //   window.Android.setFileName('haibao.png')
      //     //   window.Android.getBase64FromBlobData(url, 'image/png')
      //     // }else{

      //     // }

      //     const blob = that.base64ImgtoFile(url)
      //     that.uploadok(blob)

      //   } else {
      //     this.$message.error(response.data.msg.info);
      //   }
      // })

      // capture() {
      //   html2canvas(this.$refs.captureArea, {
      //     useCORS: true,
      //     scale: 2
      //   }).then(canvas => {
      //     const link = document.createElement('a')
      //     link.href = canvas.toDataURL('image/png')
      //     link.download = 'screenshot.png'
      //     link.click()
      //   })
      // },
      // base64ImgtoFile(dataurl, filename = 'file') {
      //   //将base64格式分割：['data:image/png;base64','XXXX']
      //   const arr = dataurl.split(',')
      //   // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
      //   // image/png
      //   const mime = arr[0].match(/:(.*?);/)[1] //image/png
      //   //[image,png] 获取图片类型后缀
      //   const suffix = mime.split('/')[1] //png
      //   const bstr = atob(arr[1]) //atob() 方法用于解码使用 base-64 编码的字符串
      //   let n = bstr.length
      //   const u8arr = new Uint8Array(n)
      //   while (n--) {
      //     u8arr[n] = bstr.charCodeAt(n)
      //   }
      //   return new File([u8arr], `${filename}.${suffix}`, {
      //     type: mime
      //   })
      // },
      // uploadok: function(file) {
      //   let name = this.getRandomChar() + '.' + file.name.split('.')[1]
      //   var that = this
      //   axios.post(`/api/qiniu/uploadtoken`, {
      //       name: name
      //     })
      //     .then(response => {
      //       if (response.data.msg.code == 0) {
      //         const observer = {
      //           next(res) {
      //             console.log(res)
      //           },
      //           error(err) {
      //             console.log(err)
      //           },
      //           complete(res) {
      //             that.$emit('guanbiloadlog')
      //             var ua = window.navigator.userAgent.toLowerCase();
      //             if (ua.match(/micromessenger/i) == 'micromessenger') {
      //               location.href = 'https://gperson.gantanhaokeji.top/' + res.key
      //             } else {
      //               location.href = 'https://gperson.gantanhaokeji.top/' + res.key + '?attname='
      //             }
      //           }
      //         }
      //         const observable = qiniu.upload(file, name, response.data.data.token, {}, {})
      //         const subscription = observable.subscribe(observer) // 上传开始
      //       } else {
      //         that.$emit('guanbiloadlog')
      //         this.$message.error(response.data.msg.info);
      //       }
      //     });
      // },
      // getRandomChar: function(len = 11) {
      //   var x = "0123456789qwertyuioplkjhgfdsazxcvbnm" // 需要什么字符这里添加
      //   var tmp = ""
      //   var timestamp = new Date().getTime();
      //   for (var i = 0; i < len; i++) {
      //     tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
      //   }
      //   return timestamp + tmp;
      // }


    }
  }
</script>
<style scoped>
  *{ margin: 0; padding: 0; box-sizing: border-box;}
</style>
